package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.mapper.RoleMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Created by 30821 on 2018/7/11.
 */
@Service
public class RoleServiceImpl implements IRoleService{
    @Autowired
    private RoleMapper mapper;

    @Override
    public void save(Role entity) {
        mapper.insert(entity);
        List<Permission> permissions = entity.getPermissions();
        if(permissions!=null){
            for(Permission permission:permissions){
                mapper.insertRelation(entity.getId(),permission.getId());
            }
        }
    }

    @Override
    public void delete(Long id) {
        mapper.deleteRelation(id);
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Role entity) {
        mapper.deleteRelation(entity.getId());
        mapper.updateByPrimaryKey(entity);
        List<Permission> permissions = entity.getPermissions();
        if(permissions!=null){
            for(Permission permission:permissions){
                mapper.insertRelation(entity.getId(),permission.getId());
            }
        }
    }

    @Override
    public Role get(Long id) {
        return mapper.selectByPrimaryKey(id
        );
    }

    @Override
    public List<Role> list() {
        return mapper.selectAll();
    }

    @Override
    public PageResult query(QueryObject qo) {
        //查总条数
        int total =  mapper.queryForCount(qo);
        if(total==0){
            return new PageResult();
        }
        //查分页数量
        List<Role> rows = mapper.queryForList(qo);
        return new PageResult(total,rows);
    }
}
